package com.cskaoyan.service.mall;

import com.cskaoyan.bean.BaseParam;
import com.cskaoyan.bean.PageDataVo;
import com.cskaoyan.bean.mall.keyword.Keyword;
import com.cskaoyan.bean.mall.keyword.KeywordExample;
import com.cskaoyan.mapper.mall.KeywordMapper;
import com.cskaoyan.utils.Constant;
import com.cskaoyan.utils.MarketPageUtil;
import com.cskaoyan.utils.ReflectionSetJavaBeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: enhui
 **/
@Service
public class KeywordServiceImpl implements KeywordService {
    @Autowired
    KeywordMapper keywordMapper;

    @Override
    public PageDataVo keywordList(String keyword, String url, BaseParam param) {
        MarketPageUtil.startPage(param);
        KeywordExample keywordExample = new KeywordExample();
        KeywordExample.Criteria criteria = keywordExample.createCriteria();
        //条件查询，判空
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andKeywordLike("%" + keyword + "%");
        }
        if (!StringUtils.isEmpty(url)) {
            criteria.andUrlLike("%" + url + "%");
        }
        criteria.andDeletedEqualTo(false);
        keywordExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        List<Keyword> keywords = keywordMapper.selectByExample(keywordExample);
        return PageDataVo.ok(keywords);
    }

    @Override
    public Keyword createKeyword(Keyword keyword) {
        ReflectionSetJavaBeanUtils.setJavaBean(keyword);
        int count = keywordMapper.insertSelective(keyword);
        if (count == 1) {
            return keyword;
        }
        return null;
    }

    public Keyword updateKeyword(Keyword keyword) {
        Date date = new Date();
        keyword.setUpdateTime(date);
        //更新
        int count = keywordMapper.updateByPrimaryKeySelective(keyword);
        //查询并返回
        if (count == 1) {
            return keywordMapper.selectByPrimaryKey(keyword.getId());
        }
        return null;
    }

    public int deleteKeyword(Keyword keyword) {
        keyword.setDeleted(true);
        //记录的updateTime是删除时间
        Date date = new Date();
        keyword.setUpdateTime(date);
        int count = keywordMapper.updateByPrimaryKeySelective(keyword);
        if (count == 1) {
            return Constant.SUCCESS;
        }
        return Constant.FAIL;
    }
}
